package com.lgy.ms.service.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Gylin
 */
@Configuration
@EnableAsync
@Component
public class SpringAsyncConfig implements AsyncConfigurer {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringAsyncConfig.class);

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int corePoolSize = 3;
        executor.setCorePoolSize(corePoolSize);
        int maxPoolSize = 10;
        executor.setMaxPoolSize(maxPoolSize);
        int queueCapacity = 10;
        executor.setQueueCapacity(queueCapacity);
        String threadNamePrefix = "async-deal-thread ";
        executor.setThreadNamePrefix(threadNamePrefix);
        // rejection-policy:当pool已经达到max size的时候，如何处理新任务 不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setKeepAliveSeconds(10000);
        executor.initialize();
        LOGGER.debug("异步处理异常、日志的线程池启动");
        return executor;
    }
}
